import 'dart:async';
import 'dart:math';

import 'package:color_dart/color_dart.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertz/components/a_button/index.dart';
import 'package:fluttertz/jsonserialize/tzuser/data.dart';
import 'package:fluttertz/utils/global.dart';
import 'package:shared_preferences/shared_preferences.dart';

//修改密碼
class Xgma extends StatefulWidget {
  Xgma({Key key}) : super(key: key);

  _XgmaState createState() => _XgmaState();
}

class _XgmaState extends State<Xgma> {
  SharedPreferences prefs;

  int startTime;

  /// 当前倒计时 時間
  int countDownTime = 0;

  /// 总倒计时时长
  final int speed = 60;

  Timer _timer;

  xgma() async {
    if (_yzm0.compareTo(_yzm) != 0) {
      G.toast('驗證碼不正确！');
      return null;
    }

    if (_mima.compareTo(_mima2) != 0) {
      G.toast('两次输入的密碼不一致！');
      return null;
    }

    try {
      Response response;
      Dio dio = Dio();
      response = await dio.post("https://aps.acciot.com.tw/api/taizhu/czmm",
          queryParameters: {"username": G.user.uname, "password": _mima});

      if (response == null) return null;

      Map<String, dynamic> resCallbackMap = response.data;

      int code = resCallbackMap['code'];
      if (code != 1) {
        G.toast('修改密碼失敗');
        return null; //返回值不对
      }

      await G.toast('修改密碼成功');
    } catch (e) {
      G.toast('修改密碼失敗');
    }
  }

  //产生随机驗證碼
  randomBit(int len) {
    String scopeF = "123456789"; //首位
    String scopeC = "0123456789"; //中间
    String result = "";
    for (int i = 0; i < len; i++) {
      if (i == 1) {
        result = scopeF[Random().nextInt(scopeF.length)];
      } else {
        result = result + scopeC[Random().nextInt(scopeC.length)];
      }
    }
    return result;
  }

  //發送驗證碼
  getVCode() async {
    String mobile = _mobile;
    if (!mobile.startsWith("+886")) {
      mobile = "+886" + mobile.substring(1);
    }

    _yzm0 = randomBit(4);
    String yzm = "驗證碼：" + _yzm0 + " [台主小幫手]";

    try {
      Response response;
      Dio dio = Dio();
      response = await dio.post("http://aps.acciot.com.tw/api/awstest/sendsms",
          queryParameters: {"mobile": mobile, "msg": yzm});

      if (response == null) return null;

      Map<String, dynamic> resCallbackMap = response.data;

      int code = resCallbackMap['code'];
      if (code != 1) {
        G.toast('發送驗證碼失敗');
        return null; //返回值不对
      }
      startTime = G.getTime();
      countDown();
      await G.toast('發送驗證碼成功');
    } catch (e) {
      G.toast('發送驗證碼失敗');
    }
  }

  String _mobile = "";
  String _mima = "";
  String _mima2 = "";
  String _yzm = "";
  String _yzm0 = ""; //發送的驗證碼

  @override
  void initState() {
    super.initState();

    // String username = G.user.uname;
    // int nowTime1 = G.getTime();

    Future.delayed(Duration.zero, () async {
      prefs = await SharedPreferences.getInstance();
      startTime = prefs.getInt('startTime');
      // G.loading.show(context);
      int nowTime = G.getTime();

      if (startTime != null && startTime > 0) {
        if (nowTime - startTime > 60) {
          prefs.remove('startTime');
        } else {
          countDown();
        }
      }
    });
    // G.loading.show(context);
    // checkjtonline(context);

  }

  checkjtonline(BuildContext context) async {
    try {
      Response response;
      Dio dio = Dio();
      //
      response = await dio.post(
          "https://aps.acciot.com.tw/api/taizhu/checkjtonline",
          queryParameters: {"jt_serial": "sdfff"});

      if (response == null) {
        return G.toast('請連接回行動網路或可連網之WIFI！');
      }

      Map<String, dynamic> resCallbackMap = response.data;

      // G.loading.hide(context);

      int code = resCallbackMap['code'];
      if (code != 1 ) {
        G.toast('機台超時沒有上線，請再重新啟動裝置， 以及確認 wifi 密碼，重新設置!');
        Future.delayed(Duration(milliseconds: 3000), () {
          Navigator.of(context).popUntil(ModalRoute.withName("/home"));
        });

      } else if (code == 1) {
        G.toast('機台已上線!');
        setState(() {

        });
      }
      // return null;
    } catch (e) {
      G.loading.hide(context);
    }
  }


  /// 倒计时
  countDown() {
    _timer = Timer.periodic(Duration(seconds: 1), (timer) async {
      int nowTime = G.getTime();
      int result = speed - (nowTime - startTime);
      if (result < 0) {
        prefs.remove('startTime');
        _timer?.cancel();
      }

      setState(() {
        countDownTime = result;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    _timer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage("lib/assets/images/tz/bg.png"),
              fit: BoxFit.cover,
            )),
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          backgroundColor: Colors.transparent,
          appBar: customAppbar(context: context, title: '修改密碼'),
          body: Container(
            color: Colors.transparent,
            padding: EdgeInsets.only(left: 35, right: 35, top: 87),
            child: Column(
              children: <Widget>[
                Container(
                  height: 55,
                  decoration: BoxDecoration(border: G.borderBottom()),
                  child: Row(
                    children: <Widget>[
                      Flexible(
                        child: TextField(
                          maxLength: 10,
                          keyboardType: TextInputType.text,
                          decoration: InputDecoration(
                              counterText: '',
                              border: InputBorder.none,
                              hintText: '請輸入手机号码',
                              hintStyle: TextStyle(
                                fontSize: 16,
                              )),
                          onChanged: (e) {
                            setState(() {
                              _mobile = e;
                            });
                          },
                        ),
                      ),
                      buildGetVCode()
                    ],
                  ),
                ),

                Container(
                  height: 55,
                  decoration: BoxDecoration(border: G.borderBottom()),
                  child: TextField(
                    keyboardType: TextInputType.text,
                    decoration: InputDecoration(
                        border: InputBorder.none,
                        hintText: '請輸入驗證碼',
                        hintStyle: TextStyle(
                          fontSize: 16,
                        )),
                    onChanged: (e) {
                      setState(() {
                        _yzm = e;
                      });
                    },
                  ),
                ),

                Container(
                  height: 55,
                  decoration: BoxDecoration(border: G.borderBottom()),
                  child: TextField(
                    keyboardType: TextInputType.text,
                    decoration: InputDecoration(
                        border: InputBorder.none,
                        hintText: '新密碼',
                        hintStyle: TextStyle(
                          fontSize: 16,
                        )),
                    onChanged: (e) {
                      setState(() {
                        _mima = e;
                      });
                    },
                  ),
                ),

                Container(
                  height: 55,
                  decoration: BoxDecoration(border: G.borderBottom()),
                  child: TextField(
                    keyboardType: TextInputType.text,
                    decoration: InputDecoration(
                        border: InputBorder.none,
                        hintText: '確認新密碼',
                        hintStyle: TextStyle(
                          fontSize: 16,
                        )),
                    onChanged: (e) {
                      setState(() {
                        _mima2 = e;
                      });
                    },
                  ),
                ),

                /// 確認
                Container(
                  margin: EdgeInsets.only(top: 20),
                  child: AButton.normal(
                      width: 300,
                      child: Text('確認',
                          style:
                          TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                      type: 'info',
                      color: hex('#fff'),
                      onPressed: () => xgma()),
                ),
              ],
            ),
          ),
        ));
  }

  Widget space(Widget child) {
    return Container(
      margin: EdgeInsets.only(right: 20),
      child: child,
    );
  }

  /// 获取驗證碼
  Container buildGetVCode() {
    return Container(
      child: AButton.normal(
          bgColor: hex('#ccfdf6e9'),
          child: Text(countDownTime <= 0
              ? "获取驗證碼"
              : countDownTime < 10
                  ? '0$countDownTime'
                  : '$countDownTime'),
          onPressed: () {
            if (countDownTime > 0) return;
            getVCode();
          }),
    );
  }
}
